package assignment4.part1;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

public class Decrypt {
	public static byte[] DecryptString(byte[] encryptedText, String password) throws Exception{
		// Create Key
		byte key[] = password.getBytes();
		DESKeySpec desKeySpec = new DESKeySpec(key);
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
		SecretKey secretKey = keyFactory.generateSecret(desKeySpec);

		// Create Cipher
		Cipher desCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
		desCipher.init(Cipher.DECRYPT_MODE, secretKey);
		
		ByteArrayInputStream bais = new ByteArrayInputStream(encryptedText);
		CipherInputStream cis = new CipherInputStream(bais, desCipher);
		
		byte[] readBytes = new byte[]{};
		byte[] toRead = new byte[512];
		
		int read = cis.read(toRead);
		while(read > -1){
			byte[] tmp = new byte[readBytes.length + read];
			System.arraycopy(readBytes, 0, tmp, 0, readBytes.length);
			System.arraycopy(toRead, 0, tmp, readBytes.length, read);
			//readBytes = S.concatBytes(readBytes, 0, readBytes.length, toRead, 0, read, "");
			readBytes = tmp;
			read = cis.read(toRead);
		}
		
		// Remove padding if there's any!
		if(readBytes.length > 0){
			byte pad = readBytes[readBytes.length - 1];
			if(pad < 9){
				boolean trim = true;
				for(int i = 2; i <= pad; i++){
					if(readBytes[readBytes.length - i] != pad){
						trim = false;
						break;
					}
				}
				
				if(trim && readBytes[readBytes.length - pad - 1] == '\n' && readBytes[readBytes.length - pad - 2] == '\r'){
					byte[] tmp = new byte[readBytes.length - pad - 2];
					System.arraycopy(readBytes, 0, tmp, 0, tmp.length);
					readBytes = tmp;
				}
			}
		}
		
		return readBytes;
	}
	
	public static String DecryptFromFile(String password, String file) throws Exception {
		// Create Key
		byte key[] = password.getBytes();
		DESKeySpec desKeySpec = new DESKeySpec(key);
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
		SecretKey secretKey = keyFactory.generateSecret(desKeySpec);

		// Create Cipher
		Cipher desCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
		desCipher.init(Cipher.DECRYPT_MODE, secretKey);

		// Create stream
		FileInputStream fis = new FileInputStream(file);
		BufferedInputStream bis = new BufferedInputStream(fis);
		CipherInputStream cis = new CipherInputStream(bis, desCipher);
		ObjectInputStream ois = new ObjectInputStream(cis);

		// Read 
		String plaintext = ois.readUTF();
		ois.close();

		return plaintext;
	}
}
